#include "GLNode.h"

GLNode::GLNode(QObject *parent) :
    QObject(parent) {
    i = new QMutableListIterator<GLNode *>(childNodes);
}

GLNode::~GLNode() {
    if (glIsList(displayList)) {
        glDeleteLists(displayList, 1);
    }
}

void GLNode::paintGL() {
    if (glIsList(displayList)) {
        glCallList(displayList);
    }
}

void GLNode::addChild(GLNode * child) {
    if (childNodes.isEmpty()) {
        nodeBoundingBox = child->getBoundingBox();
    } else {
        nodeBoundingBox = nodeBoundingBox.unite(child->getBoundingBox());
    }
    childNodes.append(child);
    compileDL();
}

GLNode * GLNode::removeChild(int childTag) {
    GLNode * child;
    for (i->toBack(); i->hasNext(); i->next()) {
        if (i->value()->getTag() == childTag) {
            child = i->value();
            i->remove();
        }
    }
    return child;
}

void GLNode::setTag(int tag) {
    nodeTag = tag;
}

int GLNode::getTag() const {
    return nodeTag;
}

QRect GLNode::getBoundingBox() const {
    return nodeBoundingBox;
}

void GLNode::setTranslation(int translateX, int translateY) {
    nodeTranslation = QPoint(translateX, translateY);
}

void GLNode::compileDL() {
    if (glIsList(displayList)) {
        glDeleteLists(displayList, 1);
    }
    displayList = glGenLists(1);
    glNewList(displayList, GL_COMPILE);
    glPushMatrix();
    glTranslatef(nodeTranslation.x(), nodeTranslation.y(), 0.0f);

    glPopMatrix();
    glEndList();
}
